<template>
  <div class="main-div">
    <div class="main-search-div">
      <el-form ref="searchRef"
               :model="state"
               status-icon
               inline>
        <el-form-item label="字典名称" prop="dictName" class="main-search-item-3">
          <el-input v-model="state.dictName" type="text"/>
        </el-form-item>
        <el-form-item label="字典key" prop="dictKey" class="main-search-item-3">
          <el-input v-model="state.dictKey" type="text"/>
        </el-form-item>
        <el-form-item label="所属模块" prop="owningModule" class="main-search-item-3">
          <el-select v-model="state.owningModule" placeholder="请选择" :clearable="true">
            <el-option v-for="item in moduleData" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :loading="searchLoading">查询</el-button>
          <el-button @click="reset(searchRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-button-div">
      <el-button type="primary" @click="addDictMainFn">新增</el-button>
      <el-popconfirm title="是否刷新缓存?" @confirm="refreshOneDictFn">
        <template #reference>
          <el-button type="danger">刷新部分缓存</el-button>
        </template>
      </el-popconfirm>
      <el-popconfirm title="是否刷新缓存?" @confirm="refreshAllDictFn">
        <template #reference>
          <el-button type="danger">刷新全部缓存</el-button>
        </template>
      </el-popconfirm>
      <el-popconfirm title="是否删除?" @confirm="delDictMainFn(0)">
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>
    </div>
    <div class="main-table-div">
      <common-page-table
          :data="tableData"
          :columns="columns"
          :pagination="pagination"
          :show-border="true"
          :need-one-select="true"
          :show-no="true"
          :loading="tableLoading"
          :show-action="true"
          :action-config="actionConfig"
          @sizeChange="sizeChange"
          @currentChange="currentChange"
          @handle-current-change="handleTableCurrentChange">
        <template #action="{row}">
            <el-button type="primary" size="small" round @click="editFn(row)">编辑</el-button>
            <el-button type="primary" size="small" round @click="editDetail(row)">编辑明细</el-button>
        </template>
      </common-page-table>
    </div>
  </div>

  <dict-main-dialog :show-dialog="mainDialog.showMainDialog"
                    :title="mainDialog.mainDialogTitle"
                    :dialog-type="mainDialog.mainDialogType"
                    :dialog-param="mainDialog.mainDialogParam"
                    @open-dialog="handleOpenMainDialog"
                    @opened-dialog="handleOpenedMainDialog"
                    @close-dialog="handleCloseMainDialog($event)"
                    @closed-dialog="handClosedMainDialog($event)"
  ></dict-main-dialog>
  <dict-detail-dialog
      :show-dialog="detailDialog.showDetailDialog"
      :dialog-title="detailDialog.detailDialogTitle"
      :dialog-param="detailDialog.detailDialogParam"
      @close-dialog="handCloseDetailDialog($event)"
  ></dict-detail-dialog>
  <el-dialog v-model="showTip"
             title="提示"
             :destroy-on-close="false"
             :close-on-click-modal="false">
    <span>{{tipContent}}</span>
    <template #footer>
      <el-button type="primary" @click="tipConfirm">确认</el-button>
      <el-button type="danger" @click="tipCancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {delMainDictReq, getMainDictListReq, refreshDictRedisReq} from '@/api/admin/dict.ts'
import {RESPONSE_CODE_SUCCESS, RESPONSE_CODE_TIP_201} from "@/config/common-config.ts";
import CommonPageTable from "@/components/common/CommonPageTable.vue";
import {dictDataUtil} from "@/utils/common-request.ts";
import {SYSTEM_MODULE} from "@/constants/dict-constants.ts";
import DictMainDialog from "@/components/manager/dict/DictMainDialog.vue";
import {DIALOG_ADD, DIALOG_EDIT} from "@/constants/common-constant.ts";
import {checkIsNull} from "@/utils/check-utils.ts";
import {elMessageTip, errorMessageTip, successMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import DictDetailDialog from "@/components/manager/dict/DictDetailDialog.vue";

interface State {
  dictName: string,
  dictKey: string,
  owningModule: string
}

const state = reactive<State>({
  dictName: '',
  dictKey: '',
  owningModule: ''
})

interface MainDialog {
  showMainDialog: boolean;
  mainDialogTitle: string;
  mainDialogType: string;
  mainDialogParam: any;
}

const mainDialog = reactive<MainDialog>({
  showMainDialog: false,
  mainDialogTitle: '',
  mainDialogType: '',
  mainDialogParam: {}
})

interface DetailDialog {
  showDetailDialog: boolean;
  detailDialogTitle: string;
  detailDialogParam: any;
}

const detailDialog = reactive<DetailDialog>({
  showDetailDialog: false,
  detailDialogTitle: '',
  detailDialogParam: {}
})

const showTip = ref<boolean>(false);
const tipContent =  ref<string>('')

const handleOpenMainDialog = () => {

}

const handleOpenedMainDialog = () => {

}

const handleCloseMainDialog = (val: boolean) => {
  mainDialog.showMainDialog = val
}

const handClosedMainDialog = (val: boolean) => {
  mainDialog.showMainDialog = val
  searchList().then()
}

const handCloseDetailDialog = (val: boolean) => {
  detailDialog.showDetailDialog = val
}

const searchRef = ref<FormInstance>()

const searchLoading = ref<boolean>(false);
const moduleData = ref<any>(() => [])
const tableData = ref<any[]>([])
const columns = [
  {prop: 'dictionaryKey', label: '字典key', width: 'auto', fixed: 'left'},
  {prop: 'dictionaryName', label: '字典名称', width: 'auto', fixed: 'left'},
  {prop: 'moduleLabel', label: '所属模块', width: 'auto'},
  {prop: 'introduce', label: '说明', width: 'auto'}
]
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const pagination = reactive({
  currentPage: currentPage.value,
  pageSize: pageSize.value,
  total: total.value
})
const tableLoading = ref<boolean>(false)
const actionConfig = {
  prop: 'action',
  label: '操作',
  width: 'auto',
}

const currentRow = ref()

const search = async () => {
  currentPage.value = 1;
  pagination.currentPage = 1
  searchList().then()
}

const searchList = async () => {
  searchLoading.value = true
  const params = {
    dictionaryKey: state.dictKey,
    dictionaryName: state.dictName,
    moduleId: state.owningModule,
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize
  }
  const res: any = await getMainDictListReq(params)
  searchLoading.value = false
  if (res.code === RESPONSE_CODE_SUCCESS) {
    tableData.value = res.data.rows;
    pagination.total = res.data.total
  }
}

const sizeChange = (val: number) => {
  pageSize.value = val;
  pagination.pageSize = val;

  searchList().then();
}

const currentChange = (val: number) => {
  currentPage.value = val;
  pagination.currentPage = val;

  searchList().then();
}

const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const initModuleData = async () => {
  moduleData.value = await dictDataUtil(SYSTEM_MODULE)
}

const addDictMainFn = () => {
  mainDialog.showMainDialog = true
  mainDialog.mainDialogTitle = '新增'
  mainDialog.mainDialogType = DIALOG_ADD
  mainDialog.mainDialogParam = {}
}

const delDictMainFn = async (secMark: number) => {
  const selectRow = currentRow.value
  if (checkIsNull(selectRow)){
    warningMessageTip("请至少选择一条数据")
    return
  }

  const params = {
    id: selectRow['id'],
    dictionaryKey: selectRow['dictionaryKey'],
    secMark: secMark
  }
  const res: any = await delMainDictReq(params);
  if (res.code === RESPONSE_CODE_SUCCESS) {
    searchList().then()
    successMessageTip(res.message)
  } else if (res.code === RESPONSE_CODE_TIP_201){
    showTip.value = true
    tipContent.value = res.message
  } else {
    errorMessageTip(res.message)
  }
}

const refreshOneDictFn = async () => {
  const selectRow = currentRow.value
  if (checkIsNull(selectRow)){
    warningMessageTip("请至少选择一条数据")
    return
  }

  const params = {
    dictionaryKey: selectRow['dictionaryName']
  }
  const res: any = await refreshDictRedisReq(params);
  elMessageTip(res.tipType, res.message)
}

const refreshAllDictFn = async () => {
  const res: any = await refreshDictRedisReq({});
  elMessageTip(res.tipType, res.message)
}

const handleTableCurrentChange = (row: any) => {
  currentRow.value = row
}

const editFn = (row: any) => {
  mainDialog.showMainDialog = true
  mainDialog.mainDialogTitle = '编辑'
  mainDialog.mainDialogType = DIALOG_EDIT
  mainDialog.mainDialogParam = row
}

const editDetail = (row: any) => {
  detailDialog.showDetailDialog = true
  detailDialog.detailDialogTitle = row['dictionaryKey'] + '明细'
  detailDialog.detailDialogParam = row
}

const tipConfirm = async () => {
  showTip.value = false
  await delDictMainFn(1);
}

const tipCancel = () => {
  showTip.value = false
}

onMounted(async () => {
  searchList().then()
  initModuleData().then()
})

</script>
